//
//  Util.swift
//  MM
//
//  Created by 李成明 on 2021/12/30.
//

import Foundation
import UIKit

enum GradientType {
    case topToBottom
    case leftToRight
    case upLeftToLowerRight
    case upRightToLowerLeft
}

private let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

class Util {    
    static func isLetterWithDigital(_ string:String) -> Bool {
        let regex = NSPredicate(format: "SELF MATCHES %@","^[0-9a-zA-Z]{1,}$")
        return regex.evaluate(with: string)
    }
    
    static func randomString(length: Int = 30) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
    
    static func compressImageData(img: UIImage) -> Data? {
        guard let data = img.pngData() else { return nil }
        
        if data.count > 500*1024 {
            let scare = CGFloat(data.count)/500*1025
            return img.jpegData(compressionQuality: 1/scare)
        }
        return data
    }

    static func gradientImage (gradientColors:[UIColor], type: GradientType, size:CGSize = CGSize(width: 30, height: 30)) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, true, 0)
        let context = UIGraphicsGetCurrentContext()
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let colors = gradientColors.map {$0.cgColor}
        guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: nil) else { return nil }
        
        var startPoint = CGPoint.zero
        var endPoint = CGPoint.zero
        switch type {
        case .topToBottom:
            startPoint = CGPoint(x: 0.5, y: 0)
            endPoint = CGPoint(x: 0.5, y: 1)
        case .leftToRight:
            startPoint = CGPoint(x: 0, y: 0.5)
            endPoint = CGPoint(x: 1, y: 0.5)
        case .upLeftToLowerRight:
            startPoint = CGPoint(x: 0, y: 0)
            endPoint = CGPoint(x: 1, y: 1)
        case .upRightToLowerLeft:
            startPoint = CGPoint(x: 1, y: 0)
            endPoint = CGPoint(x: 0, y: 1)
        }
        // 第二个参数是起始位置，第三个参数是终止位置
        context?.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 1))
        guard let cgImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil }
        UIGraphicsEndImageContext()
        return UIImage.init(cgImage: cgImage)
    }
    
    static func drawLine(start: CGPoint, end: CGPoint, color: UIColor, width: CGFloat) {
        let ctx = UIGraphicsGetCurrentContext()
        let path = CGMutablePath()
        path.move(to: start)
        color.setStroke()
        ctx?.setLineWidth(width)
        ctx?.setLineJoin(.bevel)
        ctx?.setLineCap(.butt)
        ctx?.addPath(path)
        ctx?.strokePath()
    }

    /// GCD定时器倒计时
    ///
    /// - Parameters:
    ///   - timeInterval: 间隔时间
    ///   - repeatCount: 重复次数
    ///   - handler: 循环事件,闭包参数: 1.timer 2.剩余执行次数
    static func dispatchTimer(timeInterval: Double, repeatCount: Int, handler: @escaping (DispatchSourceTimer?, Int) -> Void) {
        
        if repeatCount <= 0 {
            return
        }
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        var count = repeatCount
        timer.schedule(deadline: .now(), repeating: timeInterval)
        timer.setEventHandler {
            count -= 1
            DispatchQueue.main.async {
                handler(timer, count)
            }
            if count == 0 {
                timer.cancel()
            }
        }
        timer.resume()
    }
    
    static func rendImageWithView(_ view: UIView) -> UIImage? {
        UIGraphicsBeginImageContext(view.frame.size)
        guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
        view.layer.render(in: ctx)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
